import re
from metagpt.actions import Action
from metagpt.logs import logger
import time
from datetime import datetime
import requests

class AnalyzeCode(Action):
    
    name: str = "AnalyzeCode"
    
    ROLE_DESCRIPTION: str = """In this team, you are a senior developer in Rust programs, who are familiar with Rust features, including data types, control flows, ownership models, references and borrowing, slices, structs, common data collections, error handling, lifecycles, unit tests, I/O, functional features, closures, iterators, smart pointers, box, deref, drop, interior mutability, reference cycles, concurrency, threads, message passing, object-oriented programming and macros. You are given the Rust code snippet that is translated from a reference C/C++ program by a junior developer of your team. Are there any place that do not object to Rust features? Are there any place for effiency or clarity improvement? Is the translated code coherent to the reference C/C++ code? (i.e., free of non-existing println, different scopes of variable definition, etc.)
    You should give your thoughts in natural language, and finally sum up with a list of sentences that is useful for the junior developer to query the rust tutorial book and find the feature you mentioned. Please output your thoughts and finally give the query sentences to the junior developer. Examples of the query sentence: "How to write a function that returns a reference to a value in Rust?" or "How to write a multi-threading program with mutex enabled?". Each sentence should be in a separate line, and there should be no more than three sentences."""
    
    PROMPT_TEMPLATE: str = """{TEAM_DESCRIPTION}\n{ROLE_DESCRIPTION}
    ## Reference C/C++ Program
    {cpp_code}
    ## Input Translated code
    {translated_code}
    ## Your Question to help the junior developer (First output your thoughts. When you start to ask questions, first output `## Questions`, return the line and then output the questions)
    """

    async def run(self, team_desc: str, filenames: str):
        
        (cpp_file, translated_code_file) = filenames.split(";")
        with open(cpp_file, "r") as f:
            cpp_code = f.read()
        with open(translated_code_file, "r") as f:
            translated_code = f.read()
            
        prompt = self.PROMPT_TEMPLATE.format(TEAM_DESCRIPTION=team_desc, ROLE_DESCRIPTION=self.ROLE_DESCRIPTION, cpp_code=cpp_code, translated_code=translated_code)

        rsp = await self._aask(prompt)
        
        final_rsp = self.parse_rsp(rsp)

        timestamp = time.time()
        # 将秒数转换为日期和时间
        dt_object = datetime.fromtimestamp(timestamp)
        # 将日期和时间转换为字符串
        human_readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        data = {"time": human_readable_time,"compare":timestamp,"sender":"analyzer","receiver":"rag_agent","content":final_rsp}
        response = requests.post("http://localhost:5400/post_msg",json=data)
        response_data = response.json()
        print(response_data)
        return filenames + "\n" + final_rsp

    def parse_rsp(self, rsp: str):
        pattern = r"## Questions\n(.*)"
        match = re.search(pattern, rsp, re.DOTALL)
        questions = match.group(1) if match else ""
        print("---------- Questions from code analyze ---------")
        print(questions)
        print("---------- Questions from code analyze ---------")
        return questions.strip()


class AnalyzeCodeAfterCorrect(AnalyzeCode):
    name: str = "AnalyzeCodeAfterCorrect"
    
    ROLE_DESCRIPTION: str = """In this team, you are a senior developer in Rust programs, who are familiar with Rust features, including data types, control flows, ownership models, references and borrowing, slices, structs, common data collections, error handling, lifecycles, unit tests, I/O, functional features, closures, iterators, smart pointers, box, deref, drop, interior mutability, reference cycles, concurrency, threads, message passing, object-oriented programming and macros. You are given the Rust code snippet that is translated from a reference C/C++ program by a junior developer of your team. Previously this code snippet has some compilation errors, which might be corrected now. Are there any place that do not object to Rust features? Are there any place for effiency or clarity improvement? Is the translated code coherent to the reference C/C++ code? (i.e., free of non-existing println, different scopes of variable definition, etc.)
    You should give your thoughts in natural language, and finally sum up with a list of sentences that is useful for the junior developer to query the rust tutorial book and find the feature you mentioned. Please output your thoughts and finally give the query sentences to the junior developer. Examples of the query sentence: "How to write a function that returns a reference to a value in Rust?" or "How to write a multi-threading program with mutex enabled?". Each sentence should be in a separate line, and there should be no more than three sentences."""
    
    PROMPT_TEMPLATE: str = """{TEAM_DESCRIPTION}\n{ROLE_DESCRIPTION}
    ## Reference C/C++ Program
    {cpp_code}
    ## Input Translated code
    {translated_code}
    ## Previous Compilation Error
    {previous_error}
    ## Your Question to help the junior developer (First output your thoughts. When you start to ask questions, first output `## Questions`, return the line and then output the questions)
    """
    
    async def run(self, team_desc: str, filenames: str):
        (cpp_file, corrected_code_file, message_file) = filenames.split(";")
        with open(cpp_file, "r") as f:
            cpp_code = f.read()
        with open(corrected_code_file, "r") as f:
            corrected_code = f.read()
        with open(message_file, "r") as f:
            previous_error = f.read()
            
        prompt = self.PROMPT_TEMPLATE.format(TEAM_DESCRIPTION=team_desc, ROLE_DESCRIPTION=self.ROLE_DESCRIPTION, cpp_code=cpp_code, translated_code=corrected_code, previous_error=previous_error)

        rsp = await self._aask(prompt)

        final_rsp = self.parse_rsp(rsp)

        timestamp = time.time()
        # 将秒数转换为日期和时间
        dt_object = datetime.fromtimestamp(timestamp)
        # 将日期和时间转换为字符串
        human_readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        data = {"time": human_readable_time,"compare":timestamp,"sender":"analyzer","receiver":"rag_agent","content":final_rsp}
        response = requests.post("http://localhost:5400/post_msg",json=data)
        response_data = response.json()
        print(response_data)

        return filenames + "\n" + final_rsp
    
    def parse_rsp(self, rsp: str):
        pattern = r"## Questions\n(.*)"
        match = re.search(pattern, rsp, re.DOTALL)
        questions = match.group(1) if match else ""
        print("---------- Questions from code analyze ---------")
        print(questions)
        print("---------- Questions from code analyze ---------")
        return questions.strip()
